package liangtWorkSpace.mybatisTest.api;

import liangtWorkSpace.mybatisTest.entity.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author liangt
 * @ClassName: TestStudent
 * @title: TestStudent
 * @projectName liangtWorkSpace.old.api
 * @description: TODO
 * @date 2020/10/10 11:39
 */
public class TestStudent {

    /**
     * 测试Mybatis--Student访问
     * @MethodName main
     * @param args
     * @return
     * @throws
     * @author liangt
     * @date 2020/10/10 11:40
     */
    public static void main(String[] args) throws IOException {

        //根据配置文件获取数据库相关信息
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        //获取sql工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获取执行会话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取所有学生信息
        List<Student> studentList = sqlSession.selectList("listStudent");

        for (Student student : studentList){
            System.out.println("ID = " + student.getId() + ",Name = " + student.getName() );
        }

        //新增学生信息
        Student newStudent = new Student();
        newStudent.setId(4);
        newStudent.setName("新增一个学生");
        newStudent.setStudentID(4);
        sqlSession.insert("addStudent",newStudent);

        //删除操作
        Student delStudent = new Student();
        delStudent.setId(1);
        sqlSession.delete("delStudent",delStudent);

        //查询一个学生操作
        Student updateStudent = sqlSession.selectOne("getStudent",2);

        //更新学生操作
        updateStudent.setName("更新一个2");
        sqlSession.update("updateStudent",updateStudent);

        System.out.println("执行所有操作后测学生信息");
        //获取所有学生信息
        studentList = sqlSession.selectList("listStudent");

        for (Student student : studentList){
            System.out.println("ID = " + student.getId() + ",Name = " + student.getName() );
        }

        //清除会话缓存
        sqlSession.commit();

        // 关闭会话
        sqlSession.close();

    }

    @Test
    public void testFind() throws IOException {

        //根据配置文件获取数据库相关信息
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        //获取sql工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获取执行会话
        SqlSession sqlSession = sqlSessionFactory.openSession();

        List<Student> students = sqlSession.selectList("findStudentByName","更新");
        for (Student student:students) {
            System.out.println("ID:" + student.getId() + ",NAME:" + student.getName());
        }

    }
}
